package com.feicai.aiagent.controller;


import com.feicai.aiagent.Advisor.MyloggerAdvisor;
import com.feicai.aiagent.Advisor.Re_ReadAdvisor;
import com.feicai.aiagent.Constant.AlConstant;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;

import org.springframework.ai.tool.ToolCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Slf4j
@RestController
public class AIcontroller {

    private final ChatClient chatClient;
    @Resource
    private ToolCallback[] toolCallbacks;
    @Resource
    private Advisor loveAppRagCloudAdvisor;
   // private final MessageWindowChatMemory chatMemory;

    public AIcontroller(ChatClient.Builder builder) {
        InMemoryChatMemory chatMemory = new InMemoryChatMemory();
        //创建MessageWindowChatMemory对象，并设置chatMemoryRepository和maxMessages属性
//        this.chatMemory = MessageWindowChatMemory.builder()
//                .chatMemoryRepository(mysqlChatMemoryRepository)
//                .build();
        //创建ChatClient对象，并设置defaultAdbisors属性
        this.chatClient = builder.defaultSystem(AlConstant.System_Prompt).
                defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(chatMemory).build(),
                        //new MessageChatMemoryAdvisor(chatMemory),
                        new MyloggerAdvisor(),
                        //自定义推理增强
                        new Re_ReadAdvisor()).
                build();
    }


    @GetMapping("/chat")
    public String chat(String input) {
        log.info("input: {}", input);
        String entity = this.chatClient.prompt()
                .user(input)
                .system(AlConstant.Output_System)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, 10)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(loveAppRagCloudAdvisor)
                .tools(toolCallbacks)
                .call()
                .chatResponse().getResult().getOutput().getText();
        log.info("content: {}", entity);
        return entity;
    }
}
